<template>
  <div class="seal-registration-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>律师印章使用登记表</h2>
    </div>

    <el-card class="filter-card">
      <el-form :inline="true" :model="formInline">
        <el-form-item label="使用日期">
          <el-date-picker
            v-model="formInline.useDate"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 180px"
            placeholder="选择使用日期"
            clearable
          />
        </el-form-item>
        <el-form-item label="公章种类">
          <el-input v-model="formInline.sealType" style="width: 180px" placeholder="请输入公章种类" clearable />
        </el-form-item>
        <el-form-item label="经办人">
          <el-input v-model="formInline.handler" style="width: 180px" placeholder="请输入经办人" clearable />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit">搜索</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleAdd" icon="Plus">新增记录</el-button>
        </el-form-item>
      </el-form>
    </el-card>


    <!-- 表格容器 -->
    <el-card class="table-card">
      <div class="table-header"></div>
      <el-table
        :data="tableData"
        border
        stripe
        :header-cell-style="{ 'background-color': '#f5f7fa', 'font-weight': 'bold' }"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="useDate" label="使用日期" width="140" align="center" />
        <el-table-column prop="reason" label="使用原因" min-width="250" />
        <el-table-column prop="copies" label="份数" width="80" align="center" />
        <el-table-column prop="sealType" label="公章种类" width="180" align="center" />
        <el-table-column prop="handler" label="经办人（律师）" width="140" align="center" />
        <el-table-column prop="remarks" label="备注" min-width="200" />
        <el-table-column label="操作" width="80" align="center">
          <template #default="scope">
            <el-button
              size="small"
              type="text"
              @click="handleEdit(scope.row)"
              icon="Edit"
              title="编辑"
            />
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container" v-if="pagination.total > 0">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[2, 5, 10, 20]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <div v-else class="no-data">暂无数据</div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        class="dialog-form"
      >
        <el-form-item label="使用日期" prop="useDate">
          <el-date-picker
            v-model="formData.useDate"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="选择使用日期"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="使用原因" prop="reason">
          <el-input
            v-model="formData.reason"
            type="textarea"
            :rows="3"
            placeholder="请详细说明使用原因，包括关联的客户名称、案件信息等"
            maxlength="300"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="份数" prop="copies">
          <el-input
            v-model="formData.copies"
            placeholder="请输入份数，如：3份"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="公章种类" prop="sealType">
          <el-select
            v-model="formData.sealType"
            placeholder="请选择公章种类"
            style="width: 100%"
          >
            <el-option label="律所公章" value="律所公章" />
            <el-option label="律师执业印章" value="律师执业印章" />
            <el-option label="法律意见书专用章" value="法律意见书专用章" />
            <el-option label="合同专用章" value="合同专用章" />
            <el-option label="档案专用章" value="档案专用章" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>

        <el-form-item label="经办人（律师）" prop="handler">
          <el-input
            v-model="formData.handler"
            placeholder="请输入经办人姓名"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="formData.remarks"
            type="textarea"
            :rows="2"
            placeholder="请填写备注信息，如文件流转去向等"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确认</el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      title="印章使用记录详情"
      v-model="detailVisible"
      width="600px"
      :before-close="handleDetailClose"
    >
      <el-descriptions column="1" border>
        <el-descriptions-item label="使用日期">{{ detailData.useDate }}</el-descriptions-item>
        <el-descriptions-item label="使用原因">{{ detailData.reason }}</el-descriptions-item>
        <el-descriptions-item label="份数">{{ detailData.copies }}</el-descriptions-item>
        <el-descriptions-item label="公章种类">{{ detailData.sealType }}</el-descriptions-item>
        <el-descriptions-item label="经办人">{{ detailData.handler }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{ detailData.remarks || '无' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage, ElForm, ElFormItem, FormRules } from 'element-plus';
import { getSealsByCondition, addSeal, editSeal, getSealById } from '@/api/seal'; // 引入印章相关API

// 定义表格数据类型
interface SealRecord {
  id: string;
  useDate: string;
  reason: string;
  copies: string;
  sealType: string;
  handler: string;
  remarks: string;
}

// 页面状态
const tableData = ref<SealRecord[]>([]);
const loading = ref(false);
const submitLoading = ref(false);
const dialogVisible = ref(false);
const detailVisible = ref(false);
const dialogTitle = ref('新增记录');
const formRef = ref<InstanceType<typeof ElForm>>();
const currentRecordId = ref<string | null>(null);

// 表单数据
const formData = reactive({
  id: '',
  useDate: '',
  reason: '',
  copies: '',
  sealType: '',
  handler: '',
  remarks: ''
});

// 详情数据
const detailData = ref<Partial<SealRecord>>({});

// 搜索表单
const formInline = reactive({
  useDate: '',
  sealType: '',
  handler: '',
});

// 分页参数
const pagination = reactive({
  current: 1,
  pageSize: 2,
  total: 0
});

// 表单验证规则
const formRules = reactive<FormRules>({
  useDate: [
    { required: true, message: '请选择使用日期', trigger: 'blur' }
  ],
  reason: [
    { required: true, message: '请填写使用原因', trigger: 'blur' },
    { min: 5, message: '使用原因至少5个字符', trigger: 'blur' }
  ],
  copies: [
    { required: true, message: '请填写份数', trigger: 'blur' }
  ],
  sealType: [
    { required: true, message: '请选择公章种类', trigger: 'change' }
  ],
  handler: [
    { required: true, message: '请填写经办人姓名', trigger: 'blur' }
  ]
});

// 初始化数据
onMounted(() => {
  getSealByCondition();
});

// 搜索
const onSubmit = () => {
  pagination.current = 1;
  getSealByCondition();
};

// 重置搜索表单
const resetForm = () => {
  formInline.useDate = '';
  formInline.sealType = '';
  formInline.handler = '';
  pagination.current = 1;
  getSealByCondition();
};

// 调用API查询数据
const getSealByCondition = async () => {
  try {
    loading.value = true;
    const params = {
      ...formInline,
      page: pagination.current,
      pageSize: pagination.pageSize
    };
    const res = await getSealsByCondition(params);
    tableData.value = res.data.list || [];
    pagination.total = res.data.total || 0;
  } catch (e: any) {
    ElMessage.error(e.message || "查询失败");
  } finally {
    loading.value = false;
  }
};

// 分页处理
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  pagination.current = 1;
  getSealByCondition();
};

const handleCurrentChange = (val: number) => {
  pagination.current = val;
  getSealByCondition();
};

// 打开新增对话框
const handleAdd = () => {
  dialogTitle.value = '新增记录';
  currentRecordId.value = null;
  // 重置表单
  nextTick(() => {
    formRef.value?.resetFields();
    Object.keys(formData).forEach(key => {
      formData[key as keyof typeof formData] = '';
    });
  });
  dialogVisible.value = true;
};

// 打开编辑对话框
const handleEdit = async (row: SealRecord) => {
  try {
    loading.value = true;
    dialogTitle.value = '编辑记录';
    currentRecordId.value = row.id;

    // 调用详情接口获取最新数据
    const res = await getSealById(row.id);
    const data = res.data;

    // 填充表单数据
    formData.id = data.id;
    formData.useDate = data.useDate;
    formData.reason = data.reason;
    formData.copies = data.copies;
    formData.sealType = data.sealType;
    formData.handler = data.handler;
    formData.remarks = data.remarks;

    dialogVisible.value = true;
  } catch (e: any) {
    ElMessage.error(e.message || "获取数据失败");
  } finally {
    loading.value = false;
  }
};

// 查看详情
const handleView = async (row: SealRecord) => {
  try {
    loading.value = true;
    const res = await getSealById(row.id);
    detailData.value = res.data;
    detailVisible.value = true;
  } catch (e: any) {
    ElMessage.error(e.message || "获取详情失败");
  } finally {
    loading.value = false;
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    submitLoading.value = true;

    if (currentRecordId.value) {
      // 编辑操作
      await editSeal(formData);
      ElMessage.success('修改成功');
    } else {
      // 新增操作
      await addSeal(formData);
      ElMessage.success('新增成功');
    }

    dialogVisible.value = false;
    getSealByCondition(); // 重新加载数据
  } catch (error: any) {
    // 表单验证失败或API调用失败
    if (error.message) {
      ElMessage.error(error.message);
    }
    return;
  } finally {
    submitLoading.value = false;
  }
};

// 关闭对话框
const handleDialogClose = () => {
  formRef.value?.resetFields();
  dialogVisible.value = false;
  currentRecordId.value = null;
};

// 关闭详情对话框
const handleDetailClose = () => {
  detailVisible.value = false;
  detailData.value = {};
};
</script>

<style scoped>
.seal-registration-container {
  padding: 20px;
  background-color: #f9fafb;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #1f2329;
  font-size: 1.5rem;
}

.table-card {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border-radius: 4px;
  overflow: hidden;
  margin-top: 15px;
}

.pagination-container {
  margin-top: 16px;
  text-align: right;
}

.no-data {
  text-align: center;
  padding: 30px 0;
  color: #909399;
}

.dialog-form {
  margin-top: 10px;
}

/* 适配小屏幕 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .el-table {
    font-size: 12px;
  }

  .el-table-column {
    font-size: 12px;
  }
}
</style>
